package com.atguigu.juc.day04.cf;

import com.atguigu.juc.day04.pool.Demo01MyPool;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

public class Demo06Complete {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 1、封装一个有返回值的任务
        Supplier<String> supplier = ()->{
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "task normal result";
        };

        // 2、把封装任务的对象交给 CompletableFuture
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(supplier, Demo01MyPool.getExecutorService());

        // ※如果目标任务返回结果的时间太长，那么可以考虑在其它地方提前结束任务
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(30);
                // 调用 complete() 方法提前完成目标任务，能够传入一个和预期类型一致的数据作为兜底值
                completableFuture.complete("task completed result");
                // completableFuture.cancel(true);
            } catch (Exception e) {
                boolean cancelled = completableFuture.isCancelled();
                System.out.println("cancelled = " + cancelled);
                e.printStackTrace();
            }
        }, "thread-a").start();

        // 3、获取任务结果
        String taskResult = completableFuture.get();
        System.out.println("taskResult = " + taskResult);

    }

}
